import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:get/get.dart';

import '../../../../util/EasyInput.dart';
import '../../../../util/SearchFence.dart';
import '../../../../util/helpText_list_view.dart';
import '../controllers/edit_help_text_controller.dart';

class EditHelpTextView extends GetView<EditHelpTextController> {
  void checkDel(context,value) async {
    Get.defaultDialog(
      title: '确认删除？',
      radius: 10.0,
      barrierDismissible: false,
      content: const Text("请确认是否删除该条数据！"),
      confirm: MaterialButton(
        color: Colors.black,
        textColor: Colors.white,
        child: const Text('确认', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () async {
          Map helpText = await controller.getHelpText();
          // 查找更新
          helpText['self'].removeWhere((element) => (element.containsKey('val') && element['val'] == value['val'] && element['desc'] == value['desc']));
          controller.wordForm.value["helpText"] = json.encode(helpText);
          await controller.updateWord();
          Get.back();
          await controller.onInit();
        },
      ),
      cancel: MaterialButton(
        color: Colors.white,
        textColor: Colors.black87,
        child: const Text('取消', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  void createBox(context) async {
    Get.defaultDialog(
      title: '新增笔记',
      radius: 10.0,
      barrierDismissible: false,
      content: Container(
        decoration: BoxDecoration(
            color: Colors.white60,
            border: Border.all(color: Colors.black12, width: 1),
            borderRadius: BorderRadius.circular((10.0))),
        child: Padding(
          padding: const EdgeInsets.all(5.0),
          child: Column(
            children: [
              // name,pic,desc,typ,date,personBy,userBy
              Container(
                // padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
                // decoration: const BoxDecoration(
                //   borderRadius: BorderRadius.all(Radius.circular(15)),
                //   color: Color(0xFFF2F3F7),
                // ),
                child: Column(
                  children: [
                    EasyInput(
                      value: controller.val.text,
                      keyboardType: "text",
                      title: "内容",
                      hintText: "请输入内容：",
                      maxLines: 2,
                      values: (value) {
                        controller.val.text = value;
                      },
                    ),
                    EasyInput(
                      value: controller.desc.text,
                      keyboardType: "text",
                      title: "说明",
                      hintText: "请输入说明：",
                      values: (value) {
                        controller.desc.text = value;
                      },
                    ),
                  ],
                )
              ),
            ],
          ),
        )
        ,
      ),
      confirm: MaterialButton(
        color: Colors.black,
        textColor: Colors.white,
        child: const Text('确认', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () async {
          Map helpText = await controller.getHelpText();
          helpText['self'].add({"val":controller.val.text,"desc":controller.desc.text});
          controller.wordForm.value["helpText"] = json.encode(helpText);
          await controller.updateWord();
          Get.back();
          await controller.onInit();
        },
      ),
      cancel: MaterialButton(
        color: Colors.white,
        textColor: Colors.black87,
        child: const Text('取消', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  void updateBox(context) async {
    Get.defaultDialog(
      title: '修改笔记',
      radius: 10.0,
      barrierDismissible: false,
      content: Container(
        decoration: BoxDecoration(
            color: Colors.white60,
            border: Border.all(color: Colors.black12, width: 1),
            borderRadius: BorderRadius.circular((10.0))),
        child: Padding(
          padding: const EdgeInsets.all(5.0),
          child: Column(
            children: [
              // name,pic,desc,typ,date,personBy,userBy
              Container(
                  // padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
                  // decoration: const BoxDecoration(
                  //   borderRadius: BorderRadius.all(Radius.circular(15)),
                  //   color: Color(0xFFF2F3F7),
                  // ),
                  child: Column(
                    children: [
                      EasyInput(
                        value: controller.val.text,
                        keyboardType: "text",
                        title: "内容",
                        hintText: "请输入内容：",
                        maxLines: 2,
                        values: (value) {
                          controller.val.text = value;
                        },
                      ),
                      EasyInput(
                        value: controller.desc.text,
                        keyboardType: "text",
                        title: "说明",
                        hintText: "请输入说明：",
                        values: (value) {
                          controller.desc.text = value;
                        },
                      ),
                    ],
                  )
              ),
            ],
          ),
        )
        ,
      ),
      confirm: MaterialButton(
        color: Colors.black,
        textColor: Colors.white,
        child: const Text('确认', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () async {
          Map helpText = await controller.getHelpText();
          // 查找更新
          var thisElement = helpText['self'].firstWhere((element) => (element.containsKey('val') && element['val'] == controller.oldVal.text && element['desc'] == controller.oldDesc.text));
          thisElement['val'] = controller.val.text;
          thisElement['desc'] = controller.desc.text;
          // helpText['self'].add({"val":controller.val.text,"desc":controller.desc.text});
          controller.wordForm.value["helpText"] = json.encode(helpText);
          await controller.updateWord();
          Get.back();
          await controller.onInit();
        },
      ),
      cancel: MaterialButton(
        color: Colors.white,
        textColor: Colors.black87,
        child: const Text('取消', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        ///leading: IconButton(
        ///  icon: const Icon(Icons.density_medium_sharp),
        ///  onPressed: (){},
        ///),
          elevation: 0,
          backgroundColor: Colors.black87,
          title: const Text('单词笔记'),
          centerTitle: true
      ),
      body: Container(
        decoration: const BoxDecoration(color: Colors.white),
        child:ConstrainedBox(                          /// 约束盒子
          constraints: const BoxConstraints.expand(),  /// 不指定高和宽时则铺满整个屏慕
          child: Stack(
            alignment:Alignment.center ,               /// 指定对齐方式为居中
            children: <Widget>[                        /// 子组件列表
              controller.obx((state) => Center(
                child: controller.helpTextList.value.isNotEmpty?
                /// MyListView 是一个自定义的列表显示组件
                /// https://blog.csdn.net/weixin_40929065/article/details/123797218
                HelpTextListView(
                  datas: controller.helpTextList.value,
                  onPressed: (item) {},
                  doublePressed: (item) {
                    controller.val.text = item['val'];
                    controller.desc.text = item['desc'];
                    controller.oldVal.text = item['val'];
                    controller.oldDesc.text = item['desc'];
                    updateBox(context);
                  },
                  longPressed: (item) {
                    print(item);
                    print("长按删除");
                    checkDel(context,item);
                  },
                  onTap: (id) {
                    print(id);
                    print("点击获取id");
                  },
                  dropdown: () { controller.getHelpTextList(); },
                  pullup: () {},
                )
                    :const Text("暂无记录"),
              )),
              Positioned(
                top: 0.0,
                child:
                /// MySearchFence 是一个自定义的搜索组件
                /// https://blog.csdn.net/weixin_40929065/article/details/123638686
                SearchFence(
                  onSearch:(value){ controller.search.text = value; controller.getHelpTextList(); },
                  hasRightIcon: false,
                  rightIcon: Icons.flip,
                  onIcon:(value){ controller.search.text = value; controller.getHelpTextList(); },
                  onChange: (value) { controller.search.text = value; controller.getHelpTextList(); },
                  onClean: (value) { controller.search.text = value; controller.getHelpTextList(); },
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // backgroundColor: Colors.transparent,
        backgroundColor: Colors.white70,
        foregroundColor: Colors.black87,
        elevation: 0,
        onPressed: () {createBox(context);},
        child: const Icon(Icons.post_add_outlined),
      ),
    );
  }
}
